package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@RequestMapping("/dish")
@RestController
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;


    @PostMapping
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    public R<String> Add(@RequestBody DishDto dishDto) {
        /*String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);*/
        boolean b = dishService.saveWithFlavor(dishDto);
        return b ? R.success("添加菜品信息成功") : R.error("添加菜品信息失败");
    }


    @GetMapping("/page")
    public R<Page> list(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> PageDishDto = new Page<>();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, PageDishDto, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        Page<DishDto> dishDtoPage = PageDishDto.setRecords(list);
        return R.success(dishDtoPage);
    }


    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    public R<String> Update(@RequestBody DishDto dishDto) {
        /*String key="dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/
        boolean b = dishService.UpdateFlavor(dishDto);
        return b ? R.success("更新成功") : R.error("更新失败");
    }


    @PostMapping("/status/{status}")
    public R<String> Status(@PathVariable Integer status, Long ids[]) {
        List<Long> list = Arrays.asList(ids);
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Dish::getStatus, status).in(Dish::getId, list);
        boolean update = dishService.update(updateWrapper);
        return update ? R.success("更新状态成功") : R.error("更新状态失败");
    }


    @DeleteMapping
    public R<String> deleteByIds(@RequestParam("ids") List<Long> ids) {
        boolean b = dishService.deleteByIds(ids);
        return b ? R.success("删除成功") : R.error("删除失败");
    }



    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishdtoList=null;
        String key="dish_"+ dish.getCategoryId()+"_"+dish.getStatus();
        dishdtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishdtoList!=null){
            return R.success(dishdtoList);
        }
        LambdaQueryWrapper<Dish> QueryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        QueryWrapper.eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(QueryWrapper);
        List<DishDto> dishDtoList = list.stream().map(dish1 -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> flavors = dishFlavorService.list(wrapper);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,5, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}